﻿using AntdUI;
using BST250301.Models;
using BST250301TestStand.Models;
using BST250301TestStand.Models.Helpers;
using BST250301TestStand.Models.Utils;
using MathNet.Numerics;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Mysqlx.Crud;
using NPOI.Util;
using NPOI.Util.Collections;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace BST250301.Views
{
    public partial class ProjectSet : UserControl
    {
        private AntdUI.Window window;
        AntList<ProjectItem> antList = new AntList<ProjectItem>();
        AntList<TemplateItem> plateList = new AntList<TemplateItem>();
        int orderid = 0;
        private AppDbContext appDbContext;
        private static string currentTemplateName;
        public ProjectSet()
        {
            InitializeComponent();
            InitTableColumns();
            InitData(MainWindow.configapp.PlanName, "");
            BindEventHandler();

            currentTemplateName = this.selectSetName.Text;

            if (!MainWindow.userCurrent.ModifyEnable)
            { this.selectSetName.Visible = false; this.table_base.Visible = false; this.Enabled = false; }

        }

        private void BindEventHandler()
        {
            table_base.CellClick += Table_base_CellClick;
            table_base.CellDoubleClick += Table_base_CellDoubleClick;
            PlanSelect.PlanChanged += PlanChange;

        }
        private void Table_base_CellClick(object sender, TableClickEventArgs e)
        {
            var record = e.Record;
            if (record is ProjectItem item)
            {
                if (e.Button == MouseButtons.Right)
                {
                    if (antList.Count == 0) return;
                    int cellindex = table_base.SelectedIndex - 1;
                    if (cellindex < 0) return;

                    AntdUI.ContextMenuStrip.open(new AntdUI.ContextMenuStrip.Config(table_base,
                    (item) =>
                    {
                        if (item.Text == "删除")
                        {
                            var result = Modal.open(window, "删除警告！", "确认要删除选择的数据吗？", TType.Warn);
                            if (result == DialogResult.OK)
                            {
                                orderid = antList[cellindex].OrderID - 1;
                                antList.RemoveAt(cellindex);
                                for (int i = cellindex; i < antList.Count; i++)
                                {
                                    antList[i].OrderID = ++orderid;
                                }
                                table_base.Refresh();
                            }
                        }
                        else if (item.Text == "上移")
                        {
                            if (antList[cellindex].OrderID > 1 && cellindex > 0)
                            {
                                var noworderid = antList[cellindex].OrderID;
                                var ant = antList[cellindex];

                                antList[cellindex - 1].OrderID = noworderid;
                                antList[cellindex].OrderID = noworderid - 1;

                                antList[cellindex] = antList[cellindex - 1];
                                antList[cellindex - 1] = ant;

                                table_base.Binding(antList);
                                table_base.Refresh();
                            }
                        }
                        else if (item.Text == "下移")
                        {
                            if (antList[cellindex].OrderID > 0 && cellindex < antList.Count - 1)
                            {
                                var noworderid = antList[cellindex].OrderID;
                                var ant = antList[cellindex];

                                antList[cellindex + 1].OrderID = noworderid;
                                antList[cellindex].OrderID = noworderid + 1;

                                antList[cellindex] = antList[cellindex + 1];
                                antList[cellindex + 1] = ant;

                                table_base.Binding(antList);
                                table_base.Refresh();
                            }
                        }
                    },
                        new IContextMenuStripItem[] {

                            new AntdUI.ContextMenuStripItem("删除"){
                                IconSvg = "DeleteOutlined"
                            },
                               new AntdUI.ContextMenuStripItem("上移"){
                                IconSvg = "ArrowUpOutlined"
                            },
                                  new AntdUI.ContextMenuStripItem("下移"){
                                IconSvg = "ArrowDownOutlined"
                            },
                        }));
                }
                else
                {

                }
            }
        }
        private void PlanChange(object? sender, string planname)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<string>(PlanChange), sender, planname);
                return;
            }
            InitData(planname, "");
        }
        private async Task InitData(string planname, string selectname)
        {
            var list = DB.GetProjectNameList();

            //显示项目名称
            selectPro.Items.Clear();
            foreach (var item in list)
            {
                selectPro.Items.Add(item.Name);
            }

            selectPro.Text = list.First().Name;

            //显示当前用户拥有的测试项目
            plateList = DB.GetTestTemplate(planname);
            selectSetName.Items.Clear();
            foreach (var item in plateList)
            {
                selectSetName.Items.Add(item.TestName);
            }

            //显示当前用户项目清单
            if (string.IsNullOrEmpty(selectname))
            {
                selectSetName.Text = plateList.First().TestName;
                antList = await GetProjectAndPlateList(selectSetName.Text);
            }
            else
            {
                selectSetName.Text = selectname;
                antList = await GetProjectAndPlateList(selectname);
            }
            table_base.Binding(antList);
            table_base.Bordered = true;

            currentTemplateName = this.selectSetName.Text;
            //var host = Host.CreateDefaultBuilder()
            //   .ConfigureServices((context, services) =>
            //   {
            //       var connectionString = MainWindow.configapp.DBConnectionServer;
            //       //"Server=81.70.27.42;Database=transmissiontest;Port=8306;Uid=sa;Pwd=W1717@sina.com";
            //       services.AddDbContext<AppDbContext>(options =>
            //           options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
            //   })
            //   .Build();

            //using var scope = host.Services.CreateScope();
            //appDbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        }
        private async Task InitSelect()
        {
            var list = DB.GetProjectNameList();

            selectPro.Items.Clear();
            foreach (var item in list)
            {
                selectPro.Items.Add(item.Name);
            }
            selectPro.Text = list.First().Name;
        }
        private async Task<AntList<ProjectItem>> GetProjectAndPlateList(string name)
        {
            var list = new AntList<ProjectItem>();
            var result = DB.GetTemPlatestep(MainWindow.configapp.PlanName, name);
            foreach (var item in result)
            {
                if (item.ItemType == ProType.标准程序)
                {
                    var ret = DB.GetProjectListByCode(item.ProjectCode);
                    if (ret != null)
                    {
                        orderid = ret.OrderID = item.OrderID;
                        ret.ListRecordData = item.RecordData.Split(";").ToList();
                        ret.Note = "双击查看详情";
                        list.Add(ret);
                    }
                }
                else if (item.ItemType == ProType.前置延时)
                {
                    orderid = item.OrderID;

                    list.Add(new ProjectItem
                    {
                        Name = item.ProjectName,
                        Description = "延时工序，其他参数无效",
                        Code = item.ProjectCode,
                        ItemType = item.ItemType,
                        ConfirmWay = item.ConfirmWay,
                        PreDelay = item.PreDelay,
                        AfterDelay = item.AfterDelay,
                        Mark = MainWindow.configapp.LoginUser,
                        OrderID = item.OrderID,
                        ListRecordData = new List<string>()
                    });
                }
                else if (item.ItemType == ProType.后置延时)
                {
                    orderid = item.OrderID;

                    list.Add(new ProjectItem
                    {
                        Name = item.ProjectName,
                        Description = "延时工序，其他参数无效",
                        Code = item.ProjectCode,
                        ItemType = item.ItemType,
                        ConfirmWay = item.ConfirmWay,
                        PreDelay = item.PreDelay,
                        AfterDelay = item.AfterDelay,
                        Mark = MainWindow.configapp.LoginUser,
                        OrderID = item.OrderID,
                        ListRecordData = new List<string>()
                    });
                }
            }
            return list;
        }
        private void InitTableColumns()
        {
            table_base.Columns = new ColumnCollection() {
                new AntdUI.Column("OrderID", "序号",ColumnAlign.Center),
                new AntdUI.Column("Name", "项目名称",ColumnAlign.Center),
                new AntdUI.Column("Description", "项目描述",ColumnAlign.Center){Width ="200"},
                new AntdUI.Column("ItemType", "程序类型",ColumnAlign.Center),
                new AntdUI.Column("ConfirmWay", "工序确认",ColumnAlign.Center),
                new AntdUI.Column("TemperatureOil", "油温",ColumnAlign.Center),
                new AntdUI.Column("CFStatus", "CF状态",ColumnAlign.Center),
                new AntdUI.Column("CRStatus", "CR状态",ColumnAlign.Center),
                new AntdUI.Column("CPTOStatus", "CPTO状态",ColumnAlign.Center),
                new AntdUI.Column("MasterGearPosition", "主挡位",ColumnAlign.Center),
                new AntdUI.Column("SlaveGearPosition", "副挡位",ColumnAlign.Center),
                //new AntdUI.Column("RotateSeeped", "发动机转速",ColumnAlign.Center),
                //new AntdUI.Column("CFSetPointCurrent", "CF设置电流",ColumnAlign.Center),
                //new AntdUI.Column("CRSetPointCurrent", "CR设置电流",ColumnAlign.Center),
                //new AntdUI.Column("CPTOSetPointCurrent", "CPTO设置电流",ColumnAlign.Center),
                //new AntdUI.Column("TestCondition", "前置条件",ColumnAlign.Center),
                new AntdUI.Column("ID", "记录ID",ColumnAlign.Center),
                new AntdUI.Column("Code", "项目代码",ColumnAlign.Center),
                new AntdUI.Column("TestDuration", "测试时长",ColumnAlign.Center),
                //new AntdUI.Column("RecordData", "记录数据",ColumnAlign.Center){Width ="100"},
                new AntdUI.Column("Note", "备注",ColumnAlign.Center),
            };
        }


        private void Table_base_CellDoubleClick(object sender, TableClickEventArgs e)
        {
            if (antList.Count == 0) return;

            int cellindex = table_base.SelectedIndex - 1;
            if (cellindex < 0) return;

            var item = antList[cellindex];

            var form = new ProjectEdit(window, item);// { Size = new Size(500, 350) };           
            AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
            {
                BtnHeight = 0,
            });
            if (form.submit)
            {
                antList[cellindex] = item;
            }
        }


        private void buttonAddPro_Click(object sender, EventArgs e)
        {
            string proname = selectPro.Text;
            var result = DB.GetProjectList(proname);
            ShowSubProject(result);
            table_base.Binding(antList);
            InitSelect();
        }
        private void ShowSubProject(AntList<ProjectItem> projectItens)
        {
            try
            {
                ProjectItem item = projectItens.First();
                var form = new ProjectSub(window, item, projectItens) { Size = new Size(1200, 500) };
                AntdUI.Modal.open(new AntdUI.Modal.Config(window, "", form, TType.None)
                {
                    BtnHeight = 0,
                });
                if (form.submit)
                {
                    item.OrderID = ++orderid;
                    antList.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据错误：{ex.Message}");
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (!MainWindow.userCurrent.ApprovalEnable)
            {
                //Process.GetCurrentProcess().Kill();
                //MessageBox.Show(window, "Expiration Alert: System Error");// Your license is no longer valid. Please renew to regain full access.");
                //return;
            }
            selectSetName.Status = AntdUI.TType.None;
            if (antList.Count > 0 && selectSetName.Text.Length < 5)
            {
                selectSetName.Status = AntdUI.TType.Error;
                MessageBox.Show(window, "名称不能为空且不小于5个字符，并保持唯一不重复！");
                return;
            }

            DialogResult confirmResult = MessageBox.Show($"确认要保存当前模板[{selectSetName.Text}]吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirmResult != DialogResult.Yes)
                return;

            foreach (var item in plateList)//
            {
                if (item.TestName == selectSetName.Text)
                {
                    confirmResult = MessageBox.Show($"当前模板【{selectSetName.Text}】已存在，确认覆盖吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (confirmResult != DialogResult.Yes)
                        return;
                }
            }

            var setName = selectSetName.Text;
            bool ret = DB.SaveTestTemplate(MainWindow.configapp.PlanName, setName, "desc", (int)inputNumberRepeat.Value, MainWindow.configapp.LoginUser);
            //MessageBox.Show(ret ? "成功" : "失败", $"保存模板名称");
            if (ret)
            {
                ret = DB.DelTemplateSteps(setName, MainWindow.configapp.PlanName);

                List<TemplateItem> list = new List<TemplateItem>();
                foreach (var item in antList)
                {
                    list.Add(new TemplateItem
                    {
                        PlanName = item.PlanName,
                        TestName = item.Name,
                        ProjectName = item.Name,
                        ProjectCode = item.Code,
                        ItemType = item.ItemType,
                        ConfirmWay = item.ConfirmWay,
                        PreDelay = item.PreDelay,
                        AfterDelay = item.AfterDelay,
                        UserId = MainWindow.configapp.LoginUser,
                        RecordData = string.Join(";", item.ListRecordData == null ? new List<string>() : item.ListRecordData),
                        //ConfirmWay = plateList.Select<TemplateItem>(),
                        //PreDelay=,
                        //    AfterDelay=,
                    });
                }
                ret = DB.SaveTemplateSteps(MainWindow.configapp.PlanName, setName, antList, MainWindow.configapp.LoginUser);
                MessageBox.Show(ret ? "成功" : "失败", $"保存模板方案");
            }
            InitData(MainWindow.configapp.PlanName, setName);
        }

        private async void selectSetName_SelectedIndexChanged(object sender, IntEventArgs e)
        {
            antList = await GetProjectAndPlateList(selectSetName.Text);
            table_base.Binding(antList);
            currentTemplateName = this.selectSetName.Text;
        }

        private void buttonAddDelay_Click(object sender, EventArgs e)
        {
            ProjectItem item = new ProjectItem()
            {
                Name = $"{(int)inputNumberDelay.Value}秒延时器",
                Description = "延时工序，其他参数无效",
                Code = Guid.NewGuid().ToString("N").Substring(0, 16),
                ItemType = ProType.前置延时,
                PreDelay = (int)inputNumberDelay.Value,
                OrderID = ++orderid,
                ListRecordData = new List<string>()
            };
            antList.Add(item);
        }

        private void buttonDEL_Click(object sender, EventArgs e)
        {

            var confirmResult = MessageBox.Show($"确认清除当前存在的列表？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirmResult != DialogResult.Yes)
                return;
            orderid = 0;
            antList.Clear();
        }

        private void buttonAddNew_Click(object sender, EventArgs e)
        {
            var item = new ProjectItem()
            {
                ListRecordData = new List<string>(),
                RotateSpeed = new StepTest(),
                CRSetPointCurrent = new StepTest(),
                CFSetPointCurrent = new StepTest(),
                CPTOSetPointCurrent = new StepTest(),
                Code = Guid.NewGuid().ToString("N").Substring(0, 16),
            };
            if (antList.Count > 0)
            {
                var last = antList.Last();
                //item =last.Copy();
                item = Copy.ProjectItemCopyJson(last);
                item.Code = Guid.NewGuid().ToString("N").Substring(0, 16);
                orderid = item.OrderID;
            }
            var form = new ProjectEdit(window, item);// { Size = new Size(500, 350) };
            AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
            {
                BtnHeight = 0,
            });
            if (form.submit)
            {
                item.OrderID = ++orderid;
                antList.Add(item);
                var ret = DB.SaveProject(item, MainWindow.configapp.LoginUser);
                if (ret)
                    MessageBox.Show($"用户【{MainWindow.configapp.LoginUser}】插入到项目库一条【{item.Name}】记录。");
                InitSelect();
            }
        }

        private void buttonReOrderID_Click(object sender, EventArgs e)
        {
            orderid = 0;
            for (int i = 0; i < antList.Count; i++)
            {
                antList[i].OrderID = ++orderid;
            }
            table_base.Refresh();
        }

        private void buttonRefrence_Click(object sender, EventArgs e)
        {
            InitData(MainWindow.configapp.PlanName, selectSetName.Text);
        }

        private void buttonDeleteProject_Click(object sender, EventArgs e)
        {
            var confirmResult = MessageBox.Show($"确认删除项目【{selectSetName.Text}】？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirmResult != DialogResult.Yes)
                return;
            var ret = DB.DelTemplateSteps(selectSetName.Text, MainWindow.configapp.PlanName);
            if (ret)
            {
                ret = DB.DeleteTestTemplate(selectSetName.Text, MainWindow.configapp.PlanName);
                if (ret)
                {
                    MessageBox.Show($"用户【{MainWindow.configapp.LoginUser}】删除项目库【{selectSetName.Text}】记录。");
                    InitData(MainWindow.configapp.PlanName, "");
                }
            }
        }

        private void buttonCount_Click(object sender, EventArgs e)
        {
            var item = new ProjectItem()
            {
                ListRecordData = new List<string>(),
                RotateSpeed = new StepTest(),
                CRSetPointCurrent = new StepTest(),
                CFSetPointCurrent = new StepTest(),
                CPTOSetPointCurrent = new StepTest(),
                Code = Guid.NewGuid().ToString("N").Substring(0, 16),
            };
            var form = new ProjectEditCount(window, item);// { Size = new Size(500, 350) };
            AntdUI.Modal.open(new AntdUI.Modal.Config("", form, TType.None)
            {
                BtnHeight = 0,
            });
            if (form.submit)
            {

            }
        }
        private bool InsertTestproject(ProjectItem item)
        {
            try
            {
                return DB.SaveProject(item, MainWindow.configapp.LoginUser);
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        private void dropdown1_SelectedValueChanged(object sender, ObjectNEventArgs e)
        {
            SaveAsDeleteRename();
        }
        private void SaveAsDeleteRename()
        {
            if (!MainWindow.userCurrent.ApprovalEnable)
            {
                //Process.GetCurrentProcess().Kill();
                //MessageBox.Show(window, "Expiration Alert: System Error");// Your license is no longer valid. Please renew to regain full access.");
                //return;
            }
            DialogResult confirmResult = new DialogResult();


            var setName = selectSetName.Text.Trim();

            //save
            if (dropdown1.SelectedValue == "保存")
            {
                selectSetName.Status = AntdUI.TType.None;
                if (antList.Count > 0 && setName.Length < 5)
                {
                    selectSetName.Status = AntdUI.TType.Error;
                    MessageBox.Show(window, "名称不能为空且不小于5个字符，并保持唯一不重复！");
                    return;
                }

                if (currentTemplateName != setName)
                {
                    MessageBox.Show($"当前名称【{setName}】与原名称不一致");
                    return;
                    //改名？
                    confirmResult = MessageBox.Show($"确认要将当前模板【{currentTemplateName}】改名为【{setName}】吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (confirmResult != DialogResult.Yes)
                        return;
                    bool result = DB.SaveTestTemplate(MainWindow.configapp.PlanName, setName, "", (int)inputNumberRepeat.Value, MainWindow.configapp.LoginUser);
                    MessageBox.Show(result ? "成功" : "失败", $"保存模板方案【{setName}】");
                    return;
                }

                foreach (var item in plateList)//
                {
                    if (item.TestName == setName && currentTemplateName == setName)
                    {
                        confirmResult = MessageBox.Show($"确认保存模板【{setName}】中的修改吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (confirmResult != DialogResult.Yes)
                            return;
                        break;
                    }
                }

                bool ret = DB.SaveTestTemplate(MainWindow.configapp.PlanName, setName, "", (int)inputNumberRepeat.Value, MainWindow.configapp.LoginUser);
                //MessageBox.Show(ret ? "成功" : "失败", $"保存模板名称");
                if (ret)
                {
                    ret = DB.DelTemplateSteps(setName, MainWindow.configapp.PlanName);
                    if (ret)
                        ret = DB.SaveTemplateSteps(MainWindow.configapp.PlanName, setName, antList, MainWindow.configapp.LoginUser);
                    MessageBox.Show(ret ? "成功" : "失败", $"保存模板方案【{setName}】");
                }
                InitData(MainWindow.configapp.PlanName, setName);
            }
            //save
            else if (dropdown1.SelectedValue == "改名")
            {
                var form = new ShowDialogInput($"请输入要更改的模板名称：");
                form.ShowDialog();
                if (!form.submit)
                    return;
                string resulname = form.inputstr.Trim();
                bool ret = DB.SaveTestTemplate(MainWindow.configapp.PlanName, resulname, "", (int)inputNumberRepeat.Value, MainWindow.configapp.LoginUser);
                if (ret)
                {
                    ret = DB.DeleteTestTemplate(currentTemplateName, MainWindow.configapp.PlanName);
                    if (ret)
                    {
                        ret = DB.DelTemplateSteps(currentTemplateName, MainWindow.configapp.PlanName);
                        if (ret)
                            ret = DB.SaveTemplateSteps(MainWindow.configapp.PlanName, resulname, antList, MainWindow.configapp.LoginUser);
                    }
                    MessageBox.Show(ret ? "成功" : "失败", $"改名模板方案【{resulname}】");
                }
                InitData(MainWindow.configapp.PlanName, setName);
            }
            else if (dropdown1.SelectedValue == "另存为")
            {
                var form = new ShowDialogInput($"请输入要保存的模板名称：");
                form.ShowDialog();
                if (!form.submit)
                    return;
                string resulname = form.inputstr.Trim();
                foreach (var item in plateList)//
                {
                    if (item.TestName == resulname)
                    {
                        confirmResult = MessageBox.Show($"【{resulname}】与列表中模板名称有重复，请修改", "警告");
                        return;
                    }
                }


                bool ret = DB.SaveTestTemplate(MainWindow.configapp.PlanName, resulname, "", (int)inputNumberRepeat.Value, MainWindow.configapp.LoginUser);
                if (ret)
                {
                    List<TemplateItem> list = new List<TemplateItem>();
                    for (int i = 0; i < antList.Count; i++)// new AntList<ProjectItem>();
                    {

                        string guidcode = Guid.NewGuid().ToString("N").Substring(0, 16);
                        antList[i].Code = guidcode;
                        //var item = Copy.ProjectItemCopyJson(antList[i]);
                        //item.Code = guidcode;
                        ret = DB.SaveProject(antList[i], MainWindow.configapp.LoginUser);
                    }
                    ret = DB.SaveTemplateSteps(MainWindow.configapp.PlanName, resulname, antList, MainWindow.configapp.LoginUser);
                    MessageBox.Show(ret ? "成功" : "失败", $"保存模板方案【{resulname}】");
                }
                InitData(MainWindow.configapp.PlanName, resulname);
            }
            else if (dropdown1.SelectedValue == "删除")
            {
                confirmResult = MessageBox.Show($"确认删除项目【{setName}】？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (confirmResult != DialogResult.Yes)
                    return;
                var ret = DB.DelTemplateSteps(setName, MainWindow.configapp.PlanName);
                if (ret)
                {
                    ret = DB.DeleteTestTemplate(setName, MainWindow.configapp.PlanName);
                    if (ret)
                    {
                        MessageBox.Show($"用户【{MainWindow.configapp.LoginUser}】删除项目库【{setName}】记录。");
                        InitData(MainWindow.configapp.PlanName, "");
                    }
                }
            }
        }

        private void dropdown1_Click(object sender, EventArgs e)
        {
            dropdown1.SelectedValue = -1;
        }

        private void dropdown1_MouseEnter(object sender, EventArgs e)
        {
            dropdown1.SelectedValue = -1;
        }
    }
}
